﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Create
{
    public partial class CreatePackagePurchaseBillView : UserControl, IView
    {
        Promise _promise = new Promise();
        /// <summary>
        /// 充值客户
        /// </summary>
        WebRef.VCustomer customer = null;
        WebRef.ECustomer newCustomer = null;
        private List<WebRef.ESalesPrice> _packagePriceList;
        private string saveFlag = "";
        public CreatePackagePurchaseBillView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(this.ctlLookUpChannel, "购买渠道"));
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(this.ctlLookUpPackage, "购买套餐"));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.ctlEditMemo, "购买备注", true));
        }
        public CreatePackagePurchaseBillView(WebRef.VCustomer customer)
            : this()
        {
            this.customer = customer;
            ctlEditCustomer.Text = customer.Name;
        }
        public CreatePackagePurchaseBillView(WebRef.ECustomer newCustomer)
            : this()
        {
            this.newCustomer = newCustomer;
            ctlEditCustomer.Text = newCustomer.Name;
        }

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("save", Resources.isOK, "保存关闭", OnSaveActionClick))
                .AddAction(new ActionNode("next", Resources.isSettling, "保存并收银", OnNextActionClick))
                .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", OnCancelActionClick));
        }
        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs != null && args.ClosedArgs.Result)
            {
                if (args.ClosedArgs.ActiveArgs.TagCode == 0x01)
                {
                    newCustomer = null;
                    customer = args.ClosedArgs.Data as WebRef.VCustomer;
                    ctlEditCustomer.Tag = customer;
                    ctlEditCustomer.Text = customer.Name;
                }
            }
        }
        public void Active(ViewActiveArgs args)
        {
            //套餐销售渠道
            _promise.Then(() =>
            {
                ctlLookUpChannel.BindEMasterDataItem(_promise, Domain.Constant.MasterDataCodes.SalesChannel, null, null, false, true);
            })
                .Then(() =>
            {
                ctlSearchLookUpSalesManager.BindVStaffPosition(_promise, Domain.Constant.StaffPosts.SalesManager);
            }).Then(() =>
            {
                ctlLookUpPackage.BindEPackage(_promise, null, false);
            }).Run(null);
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("购买套餐");
        }
        #endregion

        #region actions
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnSaveActionClick(object sender, object e)
        {
            saveFlag = "";
            string message = null;
            if (!ValidationManager.Validate(this, out message))
            {
                UIContext.Current.ViewManager.ShowError(message);
                return;
            }
            _promise.Then(Save)
                .Then(() =>
                {
                    UIContext.Current.ViewManager.CloseView(true, null);
                }).Run(null);
        }
        /// <summary>
        /// 保存到收银
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnNextActionClick(object sender, object e)
        {
            saveFlag = "CheckedOut";
            _promise.Then(Save)
               .Run(null);
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnCancelActionClick(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(false, null);
        }
        /// <summary>
        /// 根据选择的套餐加载套餐项目信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlLookUpPackage_EditValueChanged(object sender, EventArgs e)
        {
            WebRef.EPackage package = ctlLookUpPackage.GetSelectedValue<WebRef.EPackage>();
            if (package == null)
            {
                return;
            }
            ctlEditExpiringDate.EditValue = package.ExpiringDate;

            _promise.Then(LoadPackageItemList)
                .Then(LoadPackagePriceList).Run();
        }
        /// <summary>
        /// 根据选择购买渠道获取套餐价值&应收金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlLookUpChannel_EditValueChanged(object sender, EventArgs e)
        {
            WebRef.EPackage package = ctlLookUpPackage.GetSelectedValue<WebRef.EPackage>();
            WebRef.EMasterDataItem selectedChannel = ctlLookUpChannel.EditValue as WebRef.EMasterDataItem;
            UpdatePriceLabel(package, selectedChannel);
        }
        #endregion

        #region methods

        /// <summary>
        /// 显示销售价格
        /// </summary>
        private void UpdatePriceLabel(WebRef.EPackage package, WebRef.EMasterDataItem selectedChannel)
        {
            if (package != null && selectedChannel != null && _packagePriceList != null)
            {
                for (int index = 0; index < _packagePriceList.Count; index++)
                {
                    if (_packagePriceList[index].Channel == selectedChannel.Code)
                    {
                        ctlEditMarketPrice.EditValue = package.MarketPrice;
                        ctlEditPrice.EditValue = _packagePriceList[index].Price;
                        this.txtSalesCom.EditValue = Domain.Calculation.CalcUtil.CalcCommissionAmount(_packagePriceList[index].Price, package.SalesCommissionType, package.SalesCommission);
                        return;
                    }
                }
            }
            this.ctlEditMarketPrice.EditValue = null;
            this.ctlEditPrice.EditValue = null;
            this.txtSalesCom.EditValue = null;
        }
        private void LoadPackagePriceList()
        {
            WebRef.EPackage package = ctlLookUpPackage.EditValue as WebRef.EPackage;
            if (package == null)
            {
                return;
            }
            UIContext.Current.InvokeAsync(() =>
            {
                ListResult<WebRef.ESalesPrice> result = new Service.QueryService().QuerySalePriceList(package.Id, Domain.Constant.SalePriceTargetTypes.Package);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        _packagePriceList = result.Data.Items;
                        _promise.Resolve();
                    }
                    else
                    {
                        _packagePriceList = null;
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }

                    UpdatePriceLabel(package, this.ctlLookUpChannel.GetSelectedValue<WebRef.EMasterDataItem>());
                }));
            });
        }
        private void LoadPackageItemList()
        {
            WebRef.EPackage package = ctlLookUpPackage.EditValue as WebRef.EPackage;
            if (package == null)
            {
                return;
            }
            UIContext.Current.InvokeAsync(() =>
            {
                ListResult<WebRef.EPackageItem> result = new Service.QueryService().QueryPackageItemList(package.Id);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        ctlGridPackageItem.DataSource = result.Data.Items;
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        /// <summary>
        /// 保存&保存并收银
        /// </summary>
        private void Save()
        {
            if (customer == null && newCustomer == null)
            {
                _promise.Reject();
                return;
            }
            WebRef.EPackage package = ctlLookUpPackage.GetSelectedValue<WebRef.EPackage>();
            if (package == null)
            {
                _promise.Reject();
                return;
            }
            WebRef.EMasterDataItem selectedChannel = ctlLookUpChannel.GetSelectedValue<WebRef.EMasterDataItem>();
            if (selectedChannel == null)
            {
                _promise.Reject();
                return;
            }
            UIContext.Current.InvokeAsync(() =>
            {
                WebRef.EPackagePurchaseBill bill = new WebRef.EPackagePurchaseBill();
                if (customer != null)
                {
                    bill.CustomerId = customer.Id;
                }
                if (newCustomer != null)
                {
                    bill.CustomerId = newCustomer.Id;
                }
                bill.BusinessId = ModuleContext.Current.BusinessId;
                bill.StationId = ModuleContext.Current.StationId;
                bill.Memo = ctlEditMemo.Text.Trim();
                bill.PackageId = package.Id;
                bill.BoughtChannel = selectedChannel.Code;
                bill.SalesManagerId = ctlSearchLookUpSalesManager.GetSelectedValue<WebRef.VStaffPosition>().GetStaffId();
                SingleResult<WebRef.EPackagePurchaseBill> result = new Service.CreateService().CreatePackagePurchaseBill(bill);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        if (this.saveFlag.Equals("CheckedOut"))
                        {
                            UIContext.Current.ViewManager.ReplaceView(new Package.CheckoutPackagePurchaseBillView(result.Data.Id));
                        }
                        else
                        {
                            UIContext.Current.ViewManager.CloseView(true, null);
                        }
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        /// <summary>
        /// 选择客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlEditCustomer_Click(object sender, EventArgs e)
        {
            UIContext.Current.ViewManager.PopupView(new Pickers.VCustomerAccuratelyPicker(), new PopupViewArgs("选择客户") { TagCode = 0x01 });
        }
        #endregion

    }
}
